﻿#include "forward_offer.h"
#include <QDebug>

Forward_Offer::Forward_Offer(const QHostAddress &address, const QJsonObject& info, QObject *parent): QTcpServer(parent)
{
    m_ClientAddress = address;
    m_ClientInfo = info;
}

Forward_Offer::~Forward_Offer()
{
    
}

void Forward_Offer::incomingConnection(qintptr socketDescriptor)
{
    
    QSslSocket* socket = new QSslSocket();
    if(!socket->setSocketDescriptor(socketDescriptor))
    {
        qDebug()<<"绑定失败";
        socket->deleteLater();
        return;
    }

    if(socket->peerAddress() == m_ClientAddress)
    {
        qDebug()<<"新offer: "<<socket->peerAddress().toString();
        //服务方的socket，存入队列
        qDebug()<<"配置SSL";
        
        QFile crt("./ssl/server.crt");
        QFile key("./ssl/server.pem");
        if(!crt.open(QIODevice::ReadOnly))
        {
            qDebug()<<"读取SSL文件错误 "<<crt.errorString();
        }
        if(!key.open(QIODevice::ReadOnly))
        {
            qDebug()<<"读取SSL文件错误 "<<key.errorString();
        }
        
        QSslConfiguration configuration;
        configuration.setLocalCertificate(QSslCertificate(&crt));
        configuration.setPrivateKey(QSslKey(&key,QSsl::Rsa, QSsl::Pem));
        configuration.setPeerVerifyMode(QSslSocket::VerifyNone);

        socket->setSslConfiguration(configuration);
        qDebug()<<"握手";
        socket->startServerEncryption();
        if(socket->waitForEncrypted()){
            qDebug()<<"waitForEncrypted success";
        }else{
            qDebug()<<"error "<<socket->errorString();
        }
        auto list = socket->sslHandshakeErrors();
        for(auto item:list){
            qDebug()<<"handshake error: "<<item.errorString();
        }
        m_QueueSocket.enqueue(socket);
        
    }
    else
    {
        
        qDebug()<<"新客户: "<<socket->peerAddress().toString();
        getOfferList:
        //取出队列处理
        if(m_QueueSocket.isEmpty())
        {
            emit addService(m_ClientInfo);
            qDebug()<<"已通知开启";
            socket->disconnectFromHost();
            socket->deleteLater();
            qDebug()<<"断开客户的连接，现在没有可用的socket服务";
            return;
        }
        QSslSocket* serverSocket= m_QueueSocket.dequeue();
        
        if(!serverSocket->isEncrypted())
        {
            if(!serverSocket->waitForEncrypted(3000))
            {
                serverSocket->disconnectFromHost();
                serverSocket->close();
                serverSocket->deleteLater();
                goto getOfferList;
            }
        }
        Forward_Task *task = new Forward_Task(serverSocket,socket);
        //connect(task,&Forward_Task::finished,this,&Forward_Offer::deleteLater);
        task->run();
    }
    
}

void Forward_Offer::RecycleSocket(QTcpSocket *socket)
{
    if(socket != nullptr)
    {
        m_QueueSocket.enqueue((QSslSocket*)socket);
    }
}
